package com.tange.ai.iot.client.gnssa.message

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.*
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.util.Consumer
import com.bumptech.glide.Glide
import com.tange.ai.iot.client.gnssa.R
import com.tange.ai.iot.client.gnssa.databinding.ActivityMessageDetailBinding
import com.tange.base.toolkit.*
import com.tange.base.ui.design.BasicDialogRequest
import com.tange.core.cloud.message.CloudMessage
import com.tange.core.cloud.message.Message
import com.tange.core.device.manage.DeviceInfoQuery
import com.tange.core.media.render.DeviceMediaRender
import com.tange.core.media.source.impl.Speed
import com.tange.core.media.source.impl.cloud.CloudStorageMediaSource
import com.tange.core.trouble.shooting.entry.DebuggingAssistant
import com.tg.appcommon.android.TGLog
import java.util.TimeZone

class MessageDetailActivity : AppCompatActivity() {

    companion object {
        private const val TAG = "MessageDetailActivity_"
        private const val PARAM_MESSAGE_ID = "PARAM_MESSAGE_ID"
        private const val PARAM_DEVICE_ID = "PARAM_DEVICE_ID"
        private const val AUTO_PLAY_AUDIO = true

        fun launch(context: Context, deviceId: String, messageId: String) {
            context.startActivity(Intent(context, MessageDetailActivity::class.java).apply {
                putExtra(PARAM_DEVICE_ID, deviceId)
                putExtra(PARAM_MESSAGE_ID, messageId)
            })
        }
    }

    private lateinit var binding: ActivityMessageDetailBinding
    private lateinit var messageId: String
    private lateinit var deviceId: String

    private var timeZone = TimeZone.getDefault()

    private var message: Message? = null
    private var containsVideo = false
    private lateinit var deviceMediaRender: DeviceMediaRender
    private lateinit var cloudStorageMediaSource: CloudStorageMediaSource

    private var paused = false

    private var lastTimeStamp = ""

    private var cloudStorageFileExits = false

    private var fastForwardEnabled = false

    private var lastAudioIcon = R.drawable.ic_baseline_volume_on_24

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        StatusBarUtil.setLightStatusBar(this, true)
        StatusNavUtils.setStatusBarColor(this, ContextCompat.getColor(this, R.color.app_background))
        requestWindowFeature(Window.FEATURE_NO_TITLE)

        messageId = intent.getStringExtra(PARAM_MESSAGE_ID)!!
        deviceId = intent.getStringExtra(PARAM_DEVICE_ID)!!

        binding = ActivityMessageDetailBinding.inflate(layoutInflater).apply {
            setContentView(root)
            supportActionBar?.hide()
            root.paddingStatusBar()
            top.left.onClicked { finish() }
            audio.onClicked { controlAudio() }
            speed.onClicked { fastForward() }
        }

        initMediaRender()

        DebuggingAssistant.attach(this, binding.devTools, true).apply {
            deviceId = this@MessageDetailActivity.deviceId
        }

        DeviceInfoQuery.requireTimezone(deviceId) { resp ->

            // 先请求设备时区（若设备不存在出海、手机与设备分处不同时区的场景，可忽略此步骤）
            resp.data?.format()?.let {
                timeZone = it
            }

            CloudMessage.queryMessageById(messageId) {
                if (it.success) it.data?.let { refresh(it) }
                else Tips.show("请求消息失败： ${it.code}, ${it.message}")
            }
        }
    }

    private fun fastForward() {
        if (fastForwardEnabled) {
            resetSpeed()
            Tips.show("已恢复正常速度")
        } else {
            cloudStorageMediaSource.setSpeed(Speed.x4)
            binding.speed.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.baseline_fast_forward_detail_enabled))
            binding.audio.isEnabled = false
            binding.audio.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_baseline_volume_off_disable_24))
            Tips.show("已启用4倍速")
        }
        fastForwardEnabled = !fastForwardEnabled
    }

    private fun resetSpeed() {
        cloudStorageMediaSource.setSpeed(Speed.x1)
        binding.speed.setImageDrawable(
            ContextCompat.getDrawable(
                this,
                R.drawable.baseline_fast_forward_detail_disable
            )
        )
        binding.audio.isEnabled = true
        binding.audio.setImageDrawable(ContextCompat.getDrawable(this, lastAudioIcon))
    }

    private fun controlAudio() {
        if (!deviceMediaRender.muted) {
            deviceMediaRender.mute(true)
            binding.audio.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.add_by_ap))
            lastAudioIcon = R.drawable.ic_baseline_volume_off_24
        } else {
            deviceMediaRender.mute(false)
            binding.audio.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_baseline_volume_on_24))
            lastAudioIcon = R.drawable.ic_baseline_volume_on_24
        }
    }

    private fun refresh(message: Message) {

        this.message = message

        binding.cover.visible()
        message.image?.let {
            Glide.with(this@MessageDetailActivity)
                .load(it)
                .error(R.drawable.light_gray_rounded_bg)
                .into(binding.cover)
        }

        message.event?.categoryName?.let { binding.msgCategoryName.text = it }
        message.event?.categoryLabel?.let { binding.msgCategoryLabel.text = it }
        message.event?.msg?.let { binding.msgDetail.text = it }
        message.startTime?.let { binding.msgTime.text = "${it.asTime(timeZone)}（设备所处时区）" }
        message.deviceId?.let { binding.msgDeviceId.text = it }

        if (message.containsVideo == true) {
            containsVideo = true
            binding.play.visible()
            binding.play.onClicked {
                play()
            }

            // 演示： 拉到后自动开始播放
            binding.playStatus.visible()
            play()

        } else {
            binding.play.gone()
        }

    }

    private fun play() {

        message?.let {
            deviceMediaRender.play(true)
            deviceMediaRender.mute(!AUTO_PLAY_AUDIO)

            if (AUTO_PLAY_AUDIO) binding.audio.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_baseline_volume_on_24))
            else binding.audio.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_baseline_volume_off_24))

            cloudStorageMediaSource.enableProduce(true)

            binding.loading.visible()
            binding.play.gone()
            paused = false

            // 提交任务，开始下载数据
            cloudStorageMediaSource.setDataSource(it.toDataSource())
            cloudStorageMediaSource.seek(it.startTime ?: 0)
        }
    }

    private fun initMediaRender() {

        cloudStorageMediaSource = CloudStorageMediaSource(this, deviceId)

        // 监听云端数据源的获取状态
        cloudStorageMediaSource.obtainStatusObserver = object : CloudStorageMediaSource.ObtainStatusObserver {

            override fun onDataSourceChanged(dataSource: CloudStorageMediaSource.DataSource) {
                cloudStorageFileExits = false
                Log.i(TAG, "[ObtainStatus-Observer][onDataSourceChanged] ${dataSource.startTime?.asTime(timeZone)} ----> ${dataSource.endTime?.asTime(timeZone)}")
            }

            override fun onStart(time: Long) {
                Log.i(TAG, "[ObtainStatus-Observer][onStart] time = ${time.asTime(timeZone)}")
            }

            override fun onError(time: Long, code: Int, message: String) {
                Log.i(TAG, "[ObtainStatus-Observer][onError] time = ${time.asTime(timeZone)}, code = $code, message = $message ")
                binding.playTimestamp.text = "云录像丢失（${time.asTime(timeZone)}）"
                binding.playTimestamp.setTextColor(Color.RED)
            }

            override fun onSuccess(time: Long) {
                cloudStorageFileExits = true
                Log.i(TAG, "[ObtainStatus-Observer][onSuccess] time = ${time.asTime(timeZone)}")
                binding.loading.gone()
            }

            override fun onComplete() {
                Log.i(TAG, "[ObtainStatus-Observer][onComplete] ")
                if (!cloudStorageFileExits) {
                    BasicDialogRequest(this@MessageDetailActivity).apply {
                        setMessage("对应的云录像全部丢失了，或者设备没有完成上传")
                        setPositiveText("知道了")
                        setPositiveOnClicked {
                            finish()
                            dismiss()
                        }
                    }.show()
                }
            }
        }

        // 创建媒体播放器
        deviceMediaRender = DeviceMediaRender(this, cloudStorageMediaSource).apply {

            mute(!AUTO_PLAY_AUDIO)

            // 将播放器示例绑定到UI上
            attach(binding.playerContainer, createCenterLayoutParams())

            // 监听首帧数据渲染回调
            observeFirstFrameRendered {
                binding.loading.gone()
                binding.cover.gone()
                binding.playStatus.visible()
            }

            // 监听播放状态
            renderStatusObserver = object : DeviceMediaRender.RenderStatusObserver {
                override fun onStart() {

                }

                override fun onComplete() {
                    Tips.show("播放完成")
                    paused = false
                    binding.play.visible()
                    resetSpeed()
                }

            }
        }

        binding.pauseResume.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.baseline_pause_circle_filled_24))
        binding.pauseResume.onClicked { pauseOrResume() }
        deviceMediaRender.onTimestampUpdate = Consumer {
            ui {
                val current = DateUtil.getStrToTime(it, timeZone)
                if (lastTimeStamp == current) return@ui
                lastTimeStamp = current
                TGLog.i(TAG, "[onTimestampUpdate] $current")

                binding.playTimestamp.text = current
                binding.playTimestamp.setTextColor(Color.WHITE)
            }
        }
    }

    // 暂停与恢复播放
    private fun pauseOrResume() {
        if (paused) {
            binding.pauseResume.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.baseline_pause_circle_filled_24))
            cloudStorageMediaSource.resume()
            deviceMediaRender.resume()
        } else {
            binding.pauseResume.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.baseline_play_circle_filled_24))
            cloudStorageMediaSource.pause()
            deviceMediaRender.pause()
        }
        paused = !paused
    }

    override fun onResume() {
        super.onResume()
        if (containsVideo) {
           play()
        }
    }

    override fun onPause() {
        super.onPause()
        if (containsVideo) {
            deviceMediaRender.reset()
            deviceMediaRender.play(false)
            cloudStorageMediaSource.enableProduce(false)
            binding.pauseResume.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.baseline_pause_circle_filled_24))
        }
    }

    private fun createCenterLayoutParams() = FrameLayout.LayoutParams(
        FrameLayout.LayoutParams.MATCH_PARENT,
        FrameLayout.LayoutParams.MATCH_PARENT
    ).apply { gravity = Gravity.CENTER }
}